<template>
  <!--  生产状态跟踪表-->
  <div class="productionStatusTracking zy-content">
    <!-- 搜索区域 -->
    <search :columns="searchData" @getSearch="getSearch(arguments)"></search>

    <!-- 列表信息 -->
    <div class="list-layout mt16">
      <div class="btns">
        <span class="title">{{ $t("common.listInformation") }}</span>
      </div>
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            :columns="columnsList"
            ellipsis
            ref="selection"
            stripe
            :data="dataArr"
            max-height="300"
        >
        </Table>
      </div>
    </div>

    <!-- 设备状态图表 -->
    <div class="list-layout mt16">
      <div class="btns little-min-b">
        <span class="title">设备状态</span>
      </div>
      <div class="chart-container" style="height: 150px">
        <timeLine
            :slice-data-list="sliceDataList"
        />
      </div>
    </div>

    <!-- 数采冲速图表 -->
    <div class="list-layout mt16">
      <div class="btns  little-min-b">
        <span class="title">数采冲速</span>
      </div>
      <div class="chart-container">
        <div ref="speedChart" class="chart"></div>
      </div>
    </div>

    <!-- 停机明细表格 -->
    <div class="list-layout mt16">
      <div class="btns ">
        <span class="title">停机明细</span>
      </div>
      <div class="tableContent">
        <Table
            class="resizable-table"
            border
            :columns="downtimeColumns"
            stripe
            :data="downtimeData"
            max-height="300"
        >
        </Table>
      </div>
    </div>

  </div>
</template>

<script>
import search from "@/components/curd/searchList.vue";
import moment from "moment";
import echarts from "echarts";
import timeLine from "@/views/dataBoard/productionStatusTracking/timeLine"

export default {
  name: "productionStatusTracking",
  components: {search, timeLine},
  data() {
    return {
      sliceDataList: [],
      yieldList: [],
      loading: false,
      searchParams: {},
      pageNum: 1,
      pageSize: 10,
      total: 0,
      downtimePageNum: 1,
      downtimeTotal: 0,
      searchData: [
        {
          title: "日期",
          key: "dateRange",
          type: "date",
          placeholder: "请选择起始日期",
          span: 4,
        },
        {
          title: '设备编号',
          key: 'deviceCode',
        },
      ],
      columnsList: [

        {
          title: "生产日期",
          key: "produceDate",
          minWidth: 180,
          align: "center",
          resizable: true,
        }, {
          title: "班次",
          key: "shift",
          minWidth: 180,
          align: "center",
          resizable: true,
        },
        {
          title: "工单号",
          key: "workCode",
          minWidth: 150,
          align: "center",
          resizable: true,
        },
        {
          title: "产品编码",
          key: "materialCode",
          minWidth: 150,
          align: "center",
          resizable: true,
        },
        {
          title: "产品名称",
          key: "materialName",
          minWidth: 180,
          align: "center",
          resizable: true,
        },
        {
          title: "模具编号",
          key: "moldCode",
          minWidth: 150,
          align: "center",
          resizable: true,
        },
        {
          title: "提报合格数量",
          key: "qualifiedQuantity",
          minWidth: 150,
          align: "center",
          resizable: true,
        },
        {
          title: "理论开机有效时间(h)",
          key: "theoryRunTime",
          minWidth: 180,
          align: "center",
          resizable: true,
        },
        {
          title: "数采运行小时(h)",
          key: "actualRunTime",
          minWidth: 180,
          align: "center",
          resizable: true,
        },  {
          title: " 人工作业时长",
          key: "laborOperationTime",
          minWidth: 180,
          align: "center",
          resizable: true,
          render: (h, params) => {
            return h("div",
                `${params.row.laborOperationTime} ${params.row.laborUnit || ''}`.trim()
            );
          }
        },
      ],
      downtimeColumns: [
        {
          title: "序号",
          key: "index",
          minWidth: 80,
          align: "center",
          resizable: true,
          render: (h, params) => {
            return h("div", (params.index + 1) + (this.downtimePageNum - 1) * this.pageSize);
          }
        },
        {
          title: "停机开始时间",
          key: "shutdownStartTime",
          minWidth: 180,
          align: "center",
          resizable: true,
        },
        {
          title: "停机结束时间",
          key: "shutdownEndTime",
          minWidth: 180,
          align: "center",
          resizable: true,
        },
        {
          title: "停机时长(min)",
          key: "shutdownDuration",
          minWidth: 150,
          align: "center",
          resizable: true,
        },
        {
          title: "停机原因",
          key: "reasonShutdown",
          minWidth: 200,
          align: "center",
          resizable: true,
        },
      ],
      dataArr: [],
      downtimeData: [],
      pageSizeOption: [10, 20, 30, 40],
      deviceStatusChart: null,
      speedChart: null
    };
  },
  mounted() {
    // this.initCharts();
  },
  beforeDestroy() {
    if (this.deviceStatusChart) {
      this.deviceStatusChart.dispose();
      this.deviceStatusChart = null;
    }
    if (this.speedChart) {
      this.speedChart.dispose();
      this.speedChart = null;
    }
  },
  methods: {
    getSearch(arg) {
      this.searchParams = JSON.parse(JSON.stringify(arg[0]));
      this.pageNum = 1;
      this.downtimePageNum = 1;
      this.searchList();
    },
    reset() {
      this.searchParams = {};
      this.changeNum();
    },
    //分页
    changeNum() {
      this.pageNum = 1;
      this.downtimePageNum = 1;
      this.searchList();
      this.searchDowntimeList();
    },
    changePageSize(pageSize) {
      this.pageSize = pageSize;
      this.searchList();
      this.searchDowntimeList();
    },
    changePageNum(val) {
      this.pageNum = val;
      this.searchList();
    },
    changeDowntimePageNum(val) {
      this.downtimePageNum = val;
      this.searchDowntimeList();
    },
    //查询列表
    searchList() {
      // const data = {
      //   "workOrderList": [//工单信息
      //     {
      //       "workCode": "1100102549001", //工单号
      //       "materialCode": "310000000959",//物料编码
      //       "materialName": "DJ-174定子铁芯（冲压）",//物料名称
      //       "qualifiedQuantity": 731.0,//提报合格数量
      //       "qualifiedWeight": null,//提报合格重量
      //       "moldCode": "DJ-174-11U",//模具编号
      //       "moldName": "DJ-174-11U",//模具名称
      //       "theoryRunTime": 10.0,//理论开机有效时间
      //       "actualRunTime": 8.11//数采运行
      //     },        {
      //       "workCode": "1100102549001", //工单号
      //       "materialCode": "310000000959",//物料编码
      //       "materialName": "DJ-174定子铁芯（冲压）",//物料名称
      //       "qualifiedQuantity": 731.0,//提报合格数量
      //       "qualifiedWeight": null,//提报合格重量
      //       "moldCode": "DJ-174-11U",//模具编号
      //       "moldName": "DJ-174-11U",//模具名称
      //       "theoryRunTime": 10.0,//理论开机有效时间
      //       "actualRunTime": 8.11//数采运行
      //     }
      //   ],
      //   "sliceDataList": [//设备状态列表
      //     {
      //       "startDateTime": "2025-08-03 12:00:00",//开始时间
      //       "endDateTime": "2025-08-03 13:55:54",//结束时间
      //       "status": 1//状态1-运行0-故障
      //     }, {
      //       "startDateTime": "2025-08-03 13:56:00",//开始时间
      //       "endDateTime": "2025-08-03 14:55:54",//结束时间
      //       "status": 1//状态1-运行0-故障
      //     }, {
      //       "startDateTime": "2025-08-03 15:00:00",//开始时间
      //       "endDateTime": "2025-08-03 16:55:54",//结束时间
      //       "status": 0//状态1-运行0-故障
      //     }, {
      //       "startDateTime": "2025-08-03 17:00:00",//开始时间
      //       "endDateTime": "2025-08-03 18:55:54",//结束时间
      //       "status": 2//状态1-运行0-故障
      //     },
      //   ],
      //   "abnormalShutdownList": [ //停机信息
      //     {
      //       "pageNum": 1,
      //       "pageSize": 10,
      //       "id": 11840,
      //       "deviceNo": "X16", //设备名称
      //       "shutdownCategory": "模具",//停机类别
      //       "shutdownStatus": null,//停机状态
      //       "reasonShutdown": "模具异常",//停机原因
      //       "shutdownStartTime": "2025-08-03 13:55:54",//停机开始时间
      //       "shutdownEndTime": "2025-08-03 15:02:54",//停机结束时间
      //       "shutdownDuration": "66.98",//停机持续时间
      //       "remarks": "",//备注
      //       "functionLocation": [
      //         "G3CBH",
      //         "G3CBH58JJC"
      //       ],
      //       "functionLocationName": "铁芯二厂/冲压制造四区",
      //       "operator": "王赖货",//开始操作人
      //       "operatorEnd": "王赖货",//结束操作人
      //       "shiftDate": "2025-08-03",//班次时间
      //       "shiftId": 247,//班次Id
      //       "shiftName": "甲班白班（10H）",
      //       "shiftEndDateTime": "2025-08-03 18:00:00",
      //       "moldCode": "DJ-341.5B"//模具号
      //     }
      //   ],
      //   "yieldList": [
      //     {
      //       "id": {
      //         "timestamp": 1754194451,
      //         "date": "2025-08-03 12:14:11"
      //       },
      //       "createTimestamp": 1754194451095,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:17:57",
      //       "timestamp": 1754194677624,
      //       "yield": 157.0
      //     },
      //     {
      //       "id": {
      //         "timestamp": 1754194511,
      //         "date": "2025-08-03 12:15:11"
      //       },
      //       "createTimestamp": 1754194511140,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:18:57",
      //       "timestamp": 1754194737505,
      //       "yield": 156.0
      //     },
      //     {
      //       "id": {
      //         "timestamp": 1754194574,
      //         "date": "2025-08-03 12:16:14"
      //       },
      //       "createTimestamp": 1754194574087,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:19:59",
      //       "timestamp": 1754194799882,
      //       "yield": 163.0
      //     },
      //     {
      //       "id": {
      //         "timestamp": 1754194634,
      //         "date": "2025-08-03 12:17:14"
      //       },
      //       "createTimestamp": 1754194634132,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:20:59",
      //       "timestamp": 1754194859770,
      //       "yield": 157.0
      //     },
      //     {
      //       "id": {
      //         "timestamp": 1754194691,
      //         "date": "2025-08-03 12:18:11"
      //       },
      //       "createTimestamp": 1754194691075,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:21:57",
      //       "timestamp": 1754194917158,
      //       "yield": 150.0
      //     },
      //     {
      //       "id": {
      //         "timestamp": 1754194751,
      //         "date": "2025-08-03 12:19:11"
      //       },
      //       "createTimestamp": 1754194751120,
      //       "deviceNo": "X14",
      //       "time": "2025-08-03 12:22:57",
      //       "timestamp": 1754194977029,
      //       "yield": 157.0
      //     }]
      // }
      // this.dataArr = data.workOrderList || [];
      // this.downtimeData = data.abnormalShutdownList || [];
      // this.yieldList = data.yieldList || []
      // this.sliceDataList = data.sliceDataList ||[]
      // this.initCharts()
      // return
      console.log(this.searchParams, '!this.searchParams')

      if (!this.searchParams.dateRange) {
        this.$Message.warning({
          content: "请选择日期",
          duration: 6,
          closable: true,
        });
        return false
      }
      // if(this.searchParams.dateRange) {
      //   const start = new Date(this.searchParams.dateRange[0]);
      //   const end = new Date(this.searchParams.dateRange[1]);
      //   const diffHours = Math.abs(end - start) / (1000 * 60 * 60); // 计算小时差
      //
      //   if(diffHours > 24) {
      //     this.$Message.warning({
      //       content: "日期范围不能超过24小时",
      //       duration: 6,
      //       closable: true,
      //     });
      //     return false;
      //   }
      // }
      if (!this.searchParams.deviceCode) {
        this.$Message.warning({
          content: "请输入设备编号",
          duration: 6,
          closable: true,
        });
        return false
      }
      const param = JSON.parse(JSON.stringify(this.searchParams));


      const dateStr = param.dateRange;
      const startDate = new Date(dateStr + 'T07:00:00Z'); // 强制 UTC 时间 07:00
      const endDate = new Date(startDate);
      endDate.setDate(endDate.getDate() + 1);

      param.reportingTimeS = startDate.toISOString().replace('T', ' ').substring(0, 19);
      param.reportingTimeE = endDate.toISOString().replace('T', ' ').substring(0, 19);
      let params = {
        ...param,
      };
      this.loading = true;
      this.axios({
        method: "post",
        url: "/dms/abnormalShutdown/sliceViewData",
        data: params,
      }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          const data = JSON.parse(JSON.stringify(res.data));
          this.dataArr = data.workOrderList || [];
          this.downtimeData = data.abnormalShutdownList || [];
          this.yieldList = data.yieldList || []
          this.sliceDataList = data.sliceDataList || []
          this.initCharts()
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    //查询停机明细
    searchDowntimeList() {
      let params = {
        pageNum: this.downtimePageNum,
        pageSize: this.pageSize,
        ...this.searchParams,
      };
      this.loading = true;
      this.axios({
        method: "post",
        url: "/dms/productionStatusTracking/downtimeList",
        data: params,
      }).then((res) => {
        this.loading = false;
        if (res.code == 200) {
          this.downtimeData = res.data.list || [];
          this.downtimeTotal = res.data.total;
        } else {
          this.$Message.warning({
            content: res.msg,
            duration: 6,
            closable: true,
          });
        }
      }).catch(() => {
        this.loading = false;
      });
    },
    //初始化图表
    initCharts() {
      // 设备状态图表
      // this.deviceStatusChart = echarts.init(this.$refs.deviceStatusChart);
      // 数采冲速图表
      this.speedChart = echarts.init(this.$refs.speedChart);
      this.updateCharts();
    },
    updateCharts() {
      const validData = this.yieldList
          .filter(item => !isNaN(item.yield))
          .map(item => ({
            time: moment(item.time).format('HH:mm'),
            fullTime: moment(item.time).format('YYYY-MM-DD HH:mm:ss'),
            showTime: item.time,
            yield: Number(item.yield)
          }));

      const speedOption = {
        tooltip: {
          trigger: 'axis',
          formatter: params => {
            const index = params[0].dataIndex;
            return `时间: ${validData[index].fullTime}<br/>冲速: ${params[0].data}`;
          }
        },
        grid: {
          left: '3%',
          right: '3%',
          bottom: '80px',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: validData.map(item => item.time),
          axisLabel: {
            fontSize: 14,
            formatter: (value, index) => {
              const date = new Date(validData[index].showTime);
              const minutes = date.getMinutes();
              const zoomState = this.speedChart.getModel().getComponent('dataZoom')[0];
              const zoomRange = zoomState ? (zoomState.end - zoomState.start) : 100;
              return zoomRange < 50 || minutes === 0 ? value : '';
            },
            interval: 0
          },
          axisTick: {
            alignWithLabel: true,
            interval: (index) => {
              const date = new Date(validData[index].showTime);
              const zoomState = this.speedChart.getModel().getComponent('dataZoom')[0];
              const zoomRange = zoomState ? (zoomState.end - zoomState.start) : 100;
              return zoomRange < 50 || date.getMinutes() === 0;
            }
          }
        },
        yAxis: {
          type: 'value',
          axisLabel: {margin: 10}
        },
        series: [{
          type: 'line',
          data: validData.map(item => item.yield),
          symbol: 'none',
          lineStyle: {width: 1},
          areaStyle: {
            color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
              {offset: 0, color: 'rgba(54,214,174,0.3)'},
              {offset: 1, color: 'rgba(54,214,174,0.1)'}
            ])
          }
        }],
        dataZoom: [{
          type: 'slider',
          xAxisIndex: 0,
          bottom: '30px',
          height: 20,
          start: 0,
          end: 100,
          handleSize: '80%',
          fillerColor: 'rgba(16, 171, 198, 0.5)'
        }]
      };

      this.speedChart.setOption(speedOption);
      window.addEventListener('resize', () => this.speedChart.resize());
    }
  }
};
</script>

<style scoped lang="scss">
.productionStatusTracking {
  .list-layout {
    background: #fff;
    border-radius: 4px;
    padding: 5px 16px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .chart-layout {
    background: #fff;
    border-radius: 4px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }

  .chart-container {
    height: 300px; // 增加容器高度
    margin-top: 16px;

    .chart {
      width: 100%;
      height: 100%;
      min-height: 250px; // 确保最小高度
    }
  }

  .btns {
    height: 50px;

    .title {
      font-size: 16px;
      font-weight: bold;
      color: #333;
    }
  }

  .tableContent {
    overflow-x: auto;
  }

  .pageWrap {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 16px;
  }
}

.little-min-b {
  margin-bottom: -20px;
}
</style>